from business.UnpackedData import UnpackedData 
import logging

class MappingFile:
    def __init__(self):
        self.mHeaderDataDef = UnpackedData("MappingFileHeader",
                                           [["id"               , "4s"],
                                            ["manifestMftIndex", "I"]])
        self.mEntryDataDef = UnpackedData("MappingFileEntry", 
                                          [["fileId"  , "I"],
                                           ["mftIndex", "I"]])
        
        self.mOffset = None
        self.mSize = None
        self.mHeader = None
        self.mEntries = list()
        
        self.mMappingIdToIndex = dict()
        self.mMappingIndexToId = dict()
        self.mMappingIndexToIdBis = dict()
    
    def parse(self, iFile, iOffset, iSize):
        logging.info("MappingFile: Offset(" + str(iOffset) + ") Size(" + str(iSize) + ")")
        self.mOffset = iOffset
        self.mSize = iSize
        
        iFile.seek(self.mOffset)
        lInput = iFile.read(self.mSize)
        lCurrentPos = 0
        
        self.mHeader, lCurrentPos = self.mHeaderDataDef.unpackWithOffset(lInput, lCurrentPos)
        logging.debug(self.mHeader)
        while(lCurrentPos < self.mSize):
            lEntry, lCurrentPos = self.mEntryDataDef.unpackWithOffset(lInput, lCurrentPos)
            logging.debug(lEntry)
            self.mEntries.append(lEntry)
        
        for lEntry in self.mEntries:
            if lEntry.fileId in self.mMappingIdToIndex:
                logging.error("Trying to add an id a second time: " + str(lEntry.fileId) + " - index: " + str(lEntry.mftIndex) + " - old_index: " + str(self.mMappingIdToIndex[lEntry.fileId]))
            else:
                self.mMappingIdToIndex[lEntry.fileId] = lEntry.mftIndex
            
            if lEntry.mftIndex in self.mMappingIndexToId:
                logging.debug("Duplicate for index: " + str(lEntry.mftIndex) + " - id: " + str(lEntry.fileId) + " - old_id: " + str(self.mMappingIndexToId[lEntry.mftIndex]))
                self.mMappingIndexToIdBis[lEntry.mftIndex] = self.mMappingIndexToId[lEntry.mftIndex]
                self.mMappingIndexToId[lEntry.mftIndex] = lEntry.fileId
            else:
                self.mMappingIndexToId[lEntry.mftIndex] = lEntry.fileId
    
    def getManifestFileIndex(self):
        return self.mHeader.manifestMftIndex
    
    def getFileIndex(self, iFileId):
        if iFileId in self.mMappingIdToIndex:
            return self.mMappingIdToIndex[iFileId]
        else:
            logging.error("File Id: " + str(iFileId) + " does not exist.")
    
    def getFileId(self, iIndex):
        if iIndex in self.mMappingIndexToId:
            return self.mMappingIndexToId[iIndex]
        else:
            logging.error("Index: " + str(iIndex) + " does not exist.")